<template>
  <q-input class="input-css" borderless ref="dom" type="text" :placeholder="props.placeholder" dense  square flat v-model="v" @click="focus"
    @blur="blur" @keydown.enter="emitEnter" />
</template>

<script>
import { onMounted, ref } from 'vue';

export default {
  props: {
    placeholder: {
      type: String,
      default: ''
    },
    initFocus: {
      type: Boolean
    },
    outFocus: {
      type: Boolean
    },
    preventScroll:{
      type:Boolean,
      default:true
    },
  },
  emits: ['enter'],
  setup(props, ctx) {
    const v = ref("")

    const dom = ref(null)
    
    const focusOptions = {
      preventScroll: props.preventScroll
    }

    function getInputEl() {
      return dom.value.$el.querySelector('input')
    }

    function focus() {
      // focus with KB popup
      const el = getInputEl()
      el.focus(focusOptions)
    }

    function noKbFocus() {
      // focus with no KB popup
      if (props.outFocus){
        return
      }
      const el = getInputEl()
      el.readOnly = true
      setTimeout(() => {
        el.focus()
        el.readOnly = false
      }, 10);
    }

    function blur(evt) {
      noKbFocus()
    }

    function emitEnter() {
      ctx.emit('enter', v.value)
    }

    function clearInput() {
      v.value = ""
    }

    onMounted(() => {
      if (props.initFocus) {
        noKbFocus()
      }
    })

    return {
      props,
      emitEnter,
      blur,
      focus,
      dom,
      v,
      noKbFocus,
      clearInput
    }
  }
}

</script>
